package com.bawei.lib_net.interceptor

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.nio.charset.StandardCharsets

/**
 *作者：lxy
 *功能:签名拦截器
 *时间：2025/5/23
 */
class HttpSignInterceptor:Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val newBuilder = request.newBuilder()
        //请求体 -》 字符串
        val json = bodyToString(request)
        val sign = createSign(json,"240111134737B4389719")
        newBuilder.addHeader("x-api-sign",sign)
        return chain.proceed(newBuilder.build())
    }



    private fun bodyToString(request: Request): String {
        val buffer = Buffer()
        request.body?.writeTo(buffer)
        return buffer.readUtf8()
    }

    private fun createSign(json: String, salt: String): String {
        val buffer = Buffer()
        buffer.write(json.toByteArray(StandardCharsets.UTF_8))
        buffer.write(salt.toByteArray(StandardCharsets.UTF_8))
        //md5加密
        return buffer.md5().hex()//十六进制
    }
}